package br.org.etec.dotcao.ws;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import br.org.etec.dotcao.exception.UserNotLoggedIn;
import br.org.etec.dotcao.model.User;
import br.org.etec.dotcao.model.UserPicture;
import br.org.etec.dotcao.utils.SessionUtils;
import br.org.etec.dotcao.ws.utils.ImageResult;
import br.org.etec.dotcao.ws.utils.UploadType;

@Path("/file/upload")
public class UploadResource {
	
	@GET
	@Path("/profile/picture")
	@Consumes({MediaType.MULTIPART_FORM_DATA})
	@Produces({MediaType.APPLICATION_JSON})
	public List<ImageResult> getUploadProfilePicture(@Context HttpServletRequest request){
		try {
			User loggedIn = SessionUtils.logged(request);
			
			String relativePath = UploadType.PROFILE.getNewPath(loggedIn.getUsername());
			String realPath = getDirectory(relativePath, request);
			
			if(ServletFileUpload.isMultipartContent(request)){
				final FileItemFactory factory = new DiskFileItemFactory();
				final ServletFileUpload fileUpload = new ServletFileUpload(factory);
				
				@SuppressWarnings("unchecked")
				final List<FileItem> items = fileUpload.parseRequest(request);
				
				List<ImageResult> result = new ArrayList<ImageResult>();
				
				if (items != null)
				{
					final Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext())
					{
						final FileItem item = iter.next();
						final String itemName = item.getName();
						final long size = item.getSize();
						
						if (item.isFormField())
						{
							continue;
						}
						
						
						String image = "profile-picture" + itemName.substring(itemName.lastIndexOf("."));
						
						UserPicture picture = new UserPicture();
						picture.setPath(relativePath + File.separator + image);
						picture.setUser(loggedIn);
						
						loggedIn.setPicture(picture);
						loggedIn.update();
						
						ImageResult imageResult = new ImageResult();
						imageResult.setName(image);
						imageResult.setUrl(picture.getPath());
						imageResult.setSize(size);
						
						result.add(imageResult);

						final File savedFile = new File(realPath + File.separator + image);
						System.out.println("Saving the file: " + savedFile.getName());
						item.write(savedFile);                               
					}
				}
				
				return result;
			}
			
			return Collections.emptyList();
		} catch (UserNotLoggedIn e) {
			e.printStackTrace();
			return Collections.emptyList();
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.emptyList();
		}
	}

	@POST
	@Path("/profile/picture")
	@Consumes({MediaType.MULTIPART_FORM_DATA})
	@Produces({MediaType.APPLICATION_JSON})
	public List<ImageResult> uploadProfilePicture(@Context HttpServletRequest request){
		try {
			User loggedIn = SessionUtils.logged(request);
			
			String relativePath = UploadType.PROFILE.getNewPath(loggedIn.getUsername());
			String realPath = getDirectory(relativePath, request);
			
			if(ServletFileUpload.isMultipartContent(request)){
				final FileItemFactory factory = new DiskFileItemFactory();
				final ServletFileUpload fileUpload = new ServletFileUpload(factory);
				
				@SuppressWarnings("unchecked")
				final List<FileItem> items = fileUpload.parseRequest(request);
				
				List<ImageResult> result = new ArrayList<ImageResult>();
				
				if (items != null)
				{
					final Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext())
					{
						final FileItem item = iter.next();
						final String itemName = item.getName();
						final long size = item.getSize();
						
						if (item.isFormField())
						{
							continue;
						}
						
						
						String image = "profile-picture" + itemName.substring(itemName.lastIndexOf("."));
						
						UserPicture picture = new UserPicture();
						picture.setPath(relativePath + File.separator + image);
						picture.setUser(loggedIn);
						
						loggedIn.setPicture(picture);
						loggedIn.update();
						
						ImageResult imageResult = new ImageResult();
						imageResult.setName(image);
						imageResult.setUrl(picture.getPath());
						imageResult.setSize(size);
						
						result.add(imageResult);
						
						final File savedFile = new File(realPath + File.separator + image);
						System.out.println("Saving the file: " + savedFile.getName());
						item.write(savedFile);                               
					}
				}
				
				return result;
			}
			
			return Collections.emptyList();
		} catch (UserNotLoggedIn e) {
			e.printStackTrace();
			return Collections.emptyList();
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.emptyList();
		}
	}
	
//	@POST
//	@Path("/profile/picture")
//	@Consumes({MediaType.MULTIPART_FORM_DATA})
//	@Produces({MediaType.APPLICATION_JSON})
//	public Message uploadProfilePicture(@Context HttpServletRequest request){
//		try {
//			User loggedIn = SessionUtils.logged(request);
//			
//			String relativePath = UploadType.PROFILE.getNewPath(loggedIn.getUsername());
//			String realPath = getDirectory(relativePath, request);
//			
//			if(ServletFileUpload.isMultipartContent(request)){
//				final FileItemFactory factory = new DiskFileItemFactory();
//				final ServletFileUpload fileUpload = new ServletFileUpload(factory);
//				
//				@SuppressWarnings("unchecked")
//				final List<FileItem> items = fileUpload.parseRequest(request);
//				
//				if (items != null)
//				{
//					final Iterator<FileItem> iter = items.iterator();
//					while (iter.hasNext())
//					{
//						final FileItem item = iter.next();
//						final String itemName = item.getName();
//						
//						if (item.isFormField())
//						{
//							continue;
//						}
//						
//						String image = "profile-picture" + itemName.substring(itemName.lastIndexOf("."));
//						
//						UserPicture picture = new UserPicture();
//						picture.setPath(relativePath + File.separator + image);
//						picture.setUser(loggedIn);
//						
//						loggedIn.setPicture(picture);
//						loggedIn.update();
//						
//						final File savedFile = new File(realPath + File.separator + image);
//						System.out.println("Saving the file: " + savedFile.getName());
//						item.write(savedFile);                               
//					}
//				}
//			}
//			
//			return new Message("SUCESSO", "Imagem carregada com sucesso.");
//		} catch (UserNotLoggedIn e) {
//			return new Message("ERRO", "Não foi encontrado nenhum usuário logado.");
//		} catch (Exception e) {
//			e.printStackTrace();
//			return new Message("ERRO", "Ocorreu um erro ao realizar o upload da imagem. Por favor, tente novamente mais tarde.");
//		}
//	}
	
	private Message processFiles(HttpServletRequest request, String path){
		try {
			if(ServletFileUpload.isMultipartContent(request)){
				final FileItemFactory factory = new DiskFileItemFactory();
				final ServletFileUpload fileUpload = new ServletFileUpload(factory);
				
				@SuppressWarnings("unchecked")
				final List<FileItem> items = fileUpload.parseRequest(request);
				
				if (items != null)
				{
					final Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext())
					{
						final FileItem item = iter.next();
						final String itemName = item.getName();
						final String fieldName = item.getFieldName();
						final String fieldValue = item.getString();
						
						if (item.isFormField())
						{
							System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
							System.out.println("Candidate Name: " + fieldValue);
						}
						else
						{
							final File savedFile = new File(path + File.separator + itemName);
							System.out.println("Saving the file: " + savedFile.getName());
							item.write(savedFile);                               
						}
					}
				}
			}
			
			return new Message("SUCESSO", "Imagem carregada com sucesso.");
		} catch (Exception e) {
			e.printStackTrace();
			return new Message("ERRO", "Ocorreu um erro ao realizar o upload da imagem. Por favor, tente novamente mais tarde.");
		}
	}

	public String getDirectory(String path, HttpServletRequest request){
		String contextPath = request.getServletContext().getContextPath();
		String contextRealPath = request.getServletContext().getRealPath(contextPath);
		contextRealPath = contextRealPath.substring(0, contextRealPath.lastIndexOf(File.separator + "dotcao"));
		
		File directory = new File(contextRealPath + File.separator + path);
		
		if(directory.exists() && directory.isFile()){
			throw new IllegalArgumentException("Caminho inválido!");
		}
		
		if(!directory.exists()){
			directory.mkdirs();
		}
		
		return directory.getAbsolutePath();
	}
	
	

}
